package com.rogchen.security.securitycustomuser.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author Rogchen rogchen128@gmail.com
 * @description:
 * @product: IntelliJ IDEA
 * @created Date: 19-11-6 14:48
 **/
@Component("authenticationFailureHandler")
public class SecurityAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Value("${security.user.failureUrl:login-error}")
    private String failureUrl;// 权限认证失败地址

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.debug(exception.getMessage() + " " + failureUrl);
        /** 跳转到指定页面 */
        String redirectUrl = "/login-error?error=" + URLEncoder.encode(exception.getMessage(),"UTF-8");
        new DefaultRedirectStrategy().sendRedirect(request, response, redirectUrl);
    }
}
